package org.skydiveapplibrary.ui;

import org.skydiveapplibrary.R;
import org.skydiveapplibrary.data.TimeUnit;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.View;
import android.widget.Spinner;
import android.widget.TextView;

public class TimeIntervalDialog extends AlertDialog
{
	// listener definition
	public interface OnTimeIntervalSetListener
	{
		void onTimeIntervalSet(TimeIntervalDialog dialog, int interval, TimeUnit timeUnit);
	}
	
	// listeners
	private OnTimeIntervalSetListener onTimeIntervalSetListener;
	private OnClickListener okClickListener = new OnClickListener()
	{
		@Override
		public void onClick(DialogInterface arg0, int arg1)
		{
			handleOKClick();
		}
	};
	private OnClickListener cancelClickListener = new OnClickListener()
	{
		@Override
		public void onClick(DialogInterface arg0, int arg1)
		{
			dismiss();
		}
	};
	
	// data
	private int mInterval = 0;
	private TimeUnit mTimeUnit = TimeUnit.Days;
	
	public TimeIntervalDialog(
			Context context,
			int interval,
			TimeUnit timeUnit,
			OnTimeIntervalSetListener onTimeIntervalSetListener)
	{
		super(context);
		
		this.onTimeIntervalSetListener = onTimeIntervalSetListener;
		
		// get view
		View view = View.inflate(context, R.layout.time_interval_dialog, null);
		
		// init view
		setView(view, 10, 10, 10, 10);
		setButton(
				context.getString(android.R.string.ok),
				okClickListener);
		setButton2(
				context.getString(android.R.string.cancel),
				cancelClickListener);
		setTitle(context.getString(R.string.time_interval_title));
		
		// init data
		mInterval = interval;
		mTimeUnit = timeUnit;
	}
	
	public void show()
	{
		super.show();
		
		// init interval
		TextView iField = (TextView)findViewById(R.id.IntervalField);
		iField.setText(FormatUtility.toNumericString(mInterval));
		// init interval unit spinner
		Spinner iuSpinner = (Spinner)findViewById(R.id.IntervalUnitField);
		TimeUnitAdapter iuAdapter = new TimeUnitAdapter(getContext());
		iuSpinner.setAdapter(iuAdapter);
		iuSpinner.setSelection(iuAdapter.indexOf(mTimeUnit));
	}
	
	private void handleOKClick()
	{
		// get interval
		TextView iField = (TextView)findViewById(R.id.IntervalField);
		String intervalStr = iField.getText() == null ? null : iField.getText().toString();
		int interval = FormatUtility.toInteger(intervalStr, 0);
		// get inerval unit
		Spinner iuSpinner = (Spinner)findViewById(R.id.IntervalUnitField);
		TimeUnit timeUnit = (TimeUnit)iuSpinner.getSelectedItem();
		
		if (onTimeIntervalSetListener != null)
		{
			onTimeIntervalSetListener.onTimeIntervalSet(this, interval, timeUnit);
		}
		
		// dismiss dialog
		dismiss();
	}
}
